package com.zy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.entity.ZyMenu;
import com.zy.entity.ZyRole;
import com.zy.entity.ZyUser;
import com.zy.mapper.ManageUserRoleMenuMappingMapper;
import com.zy.mapper.ZyRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Controller
public class ManageUserRoleMenuMappingController {
    @Autowired
    private ManageUserRoleMenuMappingMapper managePlus;
    @Autowired
    private ZyRoleMapper zyRoleMapper;

    /**
     * 添加用户
     * @param zyUser
     * @param roleId
     * @return
     */
    @PostMapping("/addZyUser")
    public String addUserRoleMenuMapping(ZyUser zyUser, Integer[] roleId, Integer pageNo) {

        //检查是否允许添加用户
        if (!ZyUserController.isRegister1 || !ZyUserController.isRegister2 || !ZyUserController.isRegister3) {
            return "redirect:/list"; //不允许添加用户
        }

        //插入user表
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(zyUser.getPassword());
        zyUser.setPassword(password);
        managePlus.saveUser(zyUser);

        //插入user_role表
        String username = zyUser.getUsername();
        Integer userId = managePlus.getUserIdByName(username);
        for (int i = 0; i < roleId.length; i++) {
            managePlus.saveUserRole(userId, roleId[i]);
        }

        return "redirect:/list?pageNo=" + pageNo;
    }

    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser")
    @ResponseBody
    public void deleteUser(String username) {
        //删除user_role
        Integer userId = managePlus.getUserIdByName(username);
        managePlus.deleteUserRole(userId);
        //删除user
        managePlus.deleteUserByName(username);
    }

    /**
     * 修改用户
     *
     */
    @RequestMapping("/updateUser")
    public String updateUser(ZyUser zyUser, Integer[] roleId, Integer pageNo) {

        //查询要修改的用户的信息
        ZyUser userById = managePlus.getUserByName(zyUser.getUsername());

        /* 如果没有修改用户的phone和email，就不进行phone和email的校验
         * 如果修改了用户的phone和email，就要对phone和email进行可用性的校验
         */
        if (!zyUser.getPhone().equals(userById.getPhone()) && !zyUser.getEmail().equals(userById.getEmail())) {
            //检查是否允许添加用户
            if (!ZyUserController.isRegister2 || !ZyUserController.isRegister3) {
                return "redirect:/list"; //不允许添加用户
            }
        }


        //修改user
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = encoder.encode(zyUser.getPassword());
        zyUser.setPassword(password);
        managePlus.updateUser(zyUser);

        //删除原user_role信息
        Integer userId = managePlus.getUserIdByName(zyUser.getUsername());
        managePlus.deleteRoleByUserId(userId);
        //添加新的user_role信息
        for (int i = 0; i < roleId.length; i++) {
            managePlus.saveUserRole(userId, roleId[i]);
        }

        return "redirect:/list?pageNo=" + pageNo;
    }

    /**
     * 修改user时role多选框的回显
     */
    @RequestMapping("/modifyUserEcho")
    @ResponseBody
    public Integer[] modifyUserEcho(String username) {
        Set<ZyRole> zyRoles = zyRoleMapper.getRoleByUserName(username);

        Integer[] roles = new Integer[zyRoles.size()];
        Iterator<ZyRole> iterator = zyRoles.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            roles[i] = iterator.next().getRoleId();
            i++;
        }
        for (Integer gg : roles) {
            System.err.println(gg);

        }
        return roles;
    }

    /**
     * 查询所有role和menu
     * @return
     */
    @RequestMapping("/roleManage")
    @ResponseBody
    public ModelAndView roleManage(@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                                    @RequestParam(value = "pageSize",defaultValue = "8")Integer pageSize) {
        ModelAndView modelAndView = new ModelAndView();

        //role分页
        IPage<ZyRole> rolePage = new Page<>(pageNo, pageSize);
        IPage<ZyRole> roles = zyRoleMapper.selectPage(rolePage, null);

        //查询所有menu
        List<ZyMenu> menus = managePlus.listMenus();

        modelAndView.addObject("roles", roles);
        modelAndView.addObject("menus", menus);
        modelAndView.setViewName("RoleManage");

        return modelAndView;
    }

    /**
     * 添加role_menu
     */
    @RequestMapping("/addRole")
    public String addRole(ZyRole zyRole, Integer[] menuId, Integer pageNo) {

        //插入role
        String roleName = "ROLE_" + zyRole.getRoleName().toUpperCase();
        zyRole.setRoleName(roleName);
        managePlus.addRole(zyRole);

        //插入role_menu
        Integer roleId = managePlus.getRoleIdByRoleName(zyRole.getRoleName());//根据roleName获取roleId
        for (int i = 0; i < menuId.length; i++) {
            managePlus.addRoleMenu(roleId, menuId[i]);
        }

        return "redirect:/roleManage?pageNo=" + pageNo;
    }

    /**
     * 修改role时role多选框的回显
     */
    @RequestMapping("/modifyRoleEcho")
    @ResponseBody
    public Integer[] roleEcho(Integer roleId) {
        return managePlus.getMenuIdByRoleId(roleId);
    }
    /**
     * 修改role&&role_menu
     */
    @RequestMapping("/modifyRole")
    public String modifyRole(ZyRole zyRole, Integer[] menuId, Integer pageNo) {
        //修改role表
        String roleName = "ROLE_" + zyRole.getRoleName().toUpperCase();
        zyRole.setRoleName(roleName);
        managePlus.updateRoleByRoleId(zyRole);

        //删除原来的role_menu信息
        managePlus.deleteRoleMenu(zyRole.getRoleId());
        //插入新的role_menu信息
        Integer roleId = managePlus.getRoleIdByRoleName(zyRole.getRoleName());//根据roleName获取roleId
        for (int i = 0; i < menuId.length; i++) {
            managePlus.addRoleMenu(roleId, menuId[i]);
        }

        return "redirect:/roleManage?pageNo=" + pageNo;
    }


    /**
     * 删除role&&role_menu
     */
    @RequestMapping("/deleteRoleMenu")
    @ResponseBody
    public void deleteRoleMenu(Integer roleId, Integer pageNo) {

        //删除role_menu
        managePlus.deleteRoleMenu(roleId);

        //删除role
        managePlus.deleteRole(roleId);
    }

}
